package cn.jdy.djgaj.admin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.authority.service.UserColumnService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.djgaj.entity.DjgajNews;
import cn.jdy.djgaj.sevice.DjgajNewsService;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;


/**
 * @title 新闻信息控制类
 * @date 2014-03-12
 */
@Controller
@RequestMapping("/djgajnews")
public class DjgajNewsCtrl extends BaseCtrl {

	@Autowired
	private DjgajNewsService newsService;
	@Autowired
	private ConfService confService;
	@Autowired
	private UserColumnService userColumnService;
	
	private DjgajNews kwd;
	//默认列表路径
	private static String viewName = "redirect:/djgajnews/list?s=";

	/**
	 * 初始化
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(DjgajNews entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/newsList.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "保存成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		User user = getUser();
		mv.addObject("userName", user.getUsername());
		//获取用户下的文章栏目id
		List<String> cIds = userColumnService.findUserColumn(user.getId());
		List<ConfValue> list = new ArrayList<ConfValue>();
		if(null != cIds && 0 < cIds.size()){
			for(String cid : cIds){
				ConfValue conf = new ConfValue();
				conf = confService.find(Long.valueOf(cid));
				list.add(conf);
			}
		}
		mv.addObject("classList", list);
		return mv;
	}

	/**
	 * 异步查询
	 * @param news
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(DjgajNews news, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", newsService.query(news, fromDate, toDate));
			
			jsonMap.put("iTotalDisplayRecords", newsService.count(news, fromDate, toDate));
			jsonMap.put("iTotalRecords", newsService.count());
			this.kwd = news;
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询新闻异常", e);
		}
		return jsonMap;
	}

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/newsDetail.jsp");
		/*mv.addObject("column", this.confService.queryByType(21, 0L));
		mv.addObject("data", id==null||id==0 ? id : this.newsService.find(id));*/
		
		//获取用户下的文章栏目id
				List<String> cIds = userColumnService.findUserColumn(getUser().getId());
				List<ConfValue> list = new ArrayList<ConfValue>();
				if(null != cIds && 0 < cIds.size()){
					for(String cid : cIds){
						ConfValue conf = new ConfValue();
						conf = confService.find(Long.valueOf(cid));
						list.add(conf);
					}
				}
				
				
				mv.addObject("column", list);
				DjgajNews datas = this.newsService.find(id);
				DjgajNews datanewsNews = new DjgajNews();
				if(id==null){//add new one
					datanewsNews.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				mv.addObject("data", id==null||id==0 ? datanewsNews : datas);
				User user = getUser();
				mv.addObject("username", user.getUsername());

		return mv;
	}

	/**
	 * 保存（更新）新闻
	 * @param news
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public Map<String, Object> save(DjgajNews news, Long pid) {
		ModelAndView mv = new ModelAndView();
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		news.setDepars(news.getDepartment());
		news.setDepartment(null);
		//
		try {
			if(pid==10471){ //公告栏
	        	news.setIscolums("1");
	        }else{
	        	news.setIscolums("0");
	        }
			
			//如果二级新闻类别为空，则使用一级类别
	       if(null == news.getColumnId()) {
	    	   news.setColumnId(pid);
	       }
			if(news.getId()==null) {// 新增文章
				//
				User user = getUser();
				news.setUserid(user.getId());
				news.setUsername(user.getUsername());
				
				//市局需要手动更改时间，如果为空则取正确时间
				if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == ""){
					news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
//				news.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				this.newsService.save(news);
				mv.setViewName(this.viewName.concat("1"));
				jsonMap.put("statusCode", 100);
			} else {//更新文章
				User user = getUser();
				news.setUserid(user.getId());
				news.setUsername(user.getUsername());	
			
				//置顶时修改时间
				if(news.getFalseCreateTime() == null || news.getFalseCreateTime() == "" || news.getTopTime().equals("1")){
					news.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}//东津公安分局
				this.newsService.update(news);
				mv.setViewName(this.viewName.concat("2"));
				jsonMap.put("statusCode", 200);
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, news.getId());
			}
			// 清理栏目列表缓存
			NginxPurgeCacheUtil.purge(1, news.getColumnId());
		} catch(Exception e) {
			jsonMap.put("statusCode", 500);
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "新闻保存异常！", e);
		}

		return jsonMap;
	}
	
	/**
	 * 删除新闻
	 * @return
	 */
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.newsService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理文章缓存
      NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除新闻异常！", e);
		}
		return mv;
	}
	
	/**
	 * 置顶/在原置顶基础上再次点击，即换为有效状态
	 * @param id
	 * @return
	 */
	/*
	@RequestMapping("/stickie/{id}")
	public ModelAndView reset(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operatee/newsList.jsp");
			if(id!=null && id!=0){
				List<YtwhNews> resultSet = this.newsService.queryStickieNewsNewsXysgajM();
				int len = resultSet.size();
				YtwhNews news = this.newsService.find(id);
				Long columnID = news.getColumnId();
				String crtStatus = news.getStatus();
				if(!crtStatus.equals("3")){
					int cnt=0;
					for(int i=0;i<len;i++){
						if(resultSet.get(i).getColumnId() == columnID) cnt++;
					}
					if(cnt==0){//保证一类新闻中只有一条新闻能被置顶
						news.setStatus("3");//置顶
					}
				}
				if(crtStatus.equals("3")){
					news.setStatus("1");//取消置顶，即换成有效状态
				}
				this.newsService.update(news);
			}
		return mv;
	}
*/
	/**
	 * 市公安局
	 * 复签：只需要发布者一人签收
	 * 未复签时，签收状态为有效状态“1”
	 * @param id
	 * @param name
	 * @return
	 */
	@RequestMapping("/counterSign/{id}")
	public ModelAndView ctsigned(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("/operatee/newsList.jsp");
		DjgajNews data = this.newsService.find(id);
		if(name.equals(data.getUsername())){
			data.setStatus("4");//已复签
		}
		this.newsService.update(data);
		return mv;
	}
}
